import os
import sys
import uuid
from datetime import datetime
from PyQt6.QtWidgets import (
    QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
    QLabel, QLineEdit, QPushButton, QListWidget, QTextEdit,
    QFileDialog, QMessageBox, QProgressBar, QListWidgetItem,
    QSplitter, QGroupBox, QStatusBar, QMenuBar, QMenu, 
    QCheckBox, QSpinBox, QTabWidget, QTableWidget, QTableWidgetItem,
    QHeaderView
)
from PyQt6.QtCore import Qt, QTimer, pyqtSlot
from PyQt6.QtGui import QAction, QIcon, QFont

from config import ConfigManager
from logger import log_manager
from utils import URLValidator, FileHelper
from downloader import EnhancedDownloader, DownloadTask, DownloadStatus


class VideoDownloaderApp(QMainWindow):
    """增强的视频下载器主界面类"""
    
    def __init__(self):
        super().__init__()
        
        # 初始化配置和组件
        self.config = ConfigManager()
        self.downloader = EnhancedDownloader()
        self.logger = log_manager.get_logger("UI")
        
        # 连接下载器信号
        self.downloader.signals.progress_updated.connect(self.on_download_progress)
        self.downloader.signals.status_changed.connect(self.on_download_status_changed)
        self.downloader.signals.download_complete.connect(self.on_download_complete)
        self.downloader.signals.error_occurred.connect(self.on_download_error)
        
        # 状态更新定时器
        self.status_timer = QTimer()
        self.status_timer.timeout.connect(self.update_status_display)
        self.status_timer.start(1000)  # 每秒更新一次
        
        self.init_ui()
        self.load_settings()
        
        log_manager.log_ui_action("应用启动")

    def init_ui(self):
        """初始化用户界面"""
        self.setWindowTitle("VideoGrabber - 专业视频下载器")
        
        # 从配置中加载窗口几何
        geometry = self.config.get("window_geometry")
        self.setGeometry(geometry["x"], geometry["y"], geometry["width"], geometry["height"])
        
        # 创建菜单栏
        self.create_menu_bar()
        
        # 创建状态栏
        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)
        self.status_bar.showMessage("就绪")
        
        # 主窗口部件
        main_widget = QWidget()
        self.setCentralWidget(main_widget)
        
        # 主布局
        main_layout = QHBoxLayout(main_widget)
        
        # 创建分割器
        splitter = QSplitter(Qt.Orientation.Horizontal)
        main_layout.addWidget(splitter)
        
        # 左侧面板 - 下载列表和控制
        left_panel = self.create_left_panel()
        splitter.addWidget(left_panel)
        
        # 右侧面板 - 输入和详情
        right_panel = self.create_right_panel()
        splitter.addWidget(right_panel)
        
        # 设置分割器比例
        splitter.setSizes([400, 500])

    def create_menu_bar(self):
        """创建菜单栏"""
        menubar = self.menuBar()
        
        # 文件菜单
        file_menu = menubar.addMenu('文件')
        
        # 添加下载
        add_action = QAction('新建下载', self)
        add_action.setShortcut('Ctrl+N')
        add_action.triggered.connect(self.focus_url_input)
        file_menu.addAction(add_action)
        
        # 清空完成的下载
        clear_action = QAction('清空已完成', self)
        clear_action.triggered.connect(self.clear_completed_downloads)
        file_menu.addAction(clear_action)
        
        file_menu.addSeparator()
        
        # 退出
        exit_action = QAction('退出', self)
        exit_action.setShortcut('Ctrl+Q')
        exit_action.triggered.connect(self.close)
        file_menu.addAction(exit_action)
        
        # 设置菜单
        settings_menu = menubar.addMenu('设置')
        
        # 偏好设置
        prefs_action = QAction('偏好设置', self)
        prefs_action.triggered.connect(self.show_preferences)
        settings_menu.addAction(prefs_action)
        
        # 查看日志
        logs_action = QAction('查看日志', self)
        logs_action.triggered.connect(self.show_logs)
        settings_menu.addAction(logs_action)
        
        # 帮助菜单
        help_menu = menubar.addMenu('帮助')
        
        # 关于
        about_action = QAction('关于', self)
        about_action.triggered.connect(self.show_about)
        help_menu.addAction(about_action)

    def create_left_panel(self):
        """创建左侧面板"""
        left_widget = QWidget()
        left_layout = QVBoxLayout(left_widget)
        
        # 下载列表组
        list_group = QGroupBox("下载任务")
        list_layout = QVBoxLayout(list_group)
        
        # 下载列表表格
        self.download_table = QTableWidget()
        self.download_table.setColumnCount(5)
        self.download_table.setHorizontalHeaderLabels(["文件名", "状态", "进度", "速度", "大小"])
        
        # 设置表格列宽
        header = self.download_table.horizontalHeader()
        header.setSectionResizeMode(0, QHeaderView.ResizeMode.Stretch)
        header.setSectionResizeMode(1, QHeaderView.ResizeMode.Fixed)
        header.setSectionResizeMode(2, QHeaderView.ResizeMode.Fixed)
        header.setSectionResizeMode(3, QHeaderView.ResizeMode.Fixed)
        header.setSectionResizeMode(4, QHeaderView.ResizeMode.Fixed)
        
        self.download_table.setColumnWidth(1, 80)
        self.download_table.setColumnWidth(2, 80)
        self.download_table.setColumnWidth(3, 100)
        self.download_table.setColumnWidth(4, 80)
        
        self.download_table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
        self.download_table.itemSelectionChanged.connect(self.on_download_selected)
        
        list_layout.addWidget(self.download_table)
        
        # 控制按钮
        controls_layout = QHBoxLayout()
        
        self.pause_btn = QPushButton("暂停")
        self.pause_btn.setObjectName("pauseButton")
        self.pause_btn.clicked.connect(self.pause_download)
        self.pause_btn.setEnabled(False)
        
        self.resume_btn = QPushButton("恢复")
        self.resume_btn.clicked.connect(self.resume_download)
        self.resume_btn.setEnabled(False)
        
        self.cancel_btn = QPushButton("取消")
        self.cancel_btn.setObjectName("cancelButton")
        self.cancel_btn.clicked.connect(self.cancel_download)
        self.cancel_btn.setEnabled(False)
        
        self.retry_btn = QPushButton("重试")
        self.retry_btn.clicked.connect(self.retry_download)
        self.retry_btn.setEnabled(False)
        
        self.remove_btn = QPushButton("移除")
        self.remove_btn.clicked.connect(self.remove_download)
        self.remove_btn.setEnabled(False)
        
        controls_layout.addWidget(self.pause_btn)
        controls_layout.addWidget(self.resume_btn)
        controls_layout.addWidget(self.cancel_btn)
        controls_layout.addWidget(self.retry_btn)
        controls_layout.addWidget(self.remove_btn)
        controls_layout.addStretch()
        
        list_layout.addLayout(controls_layout)
        left_layout.addWidget(list_group)
        
        return left_widget

    def create_right_panel(self):
        """创建右侧面板"""
        right_widget = QWidget()
        right_layout = QVBoxLayout(right_widget)
        
        # 输入组
        input_group = QGroupBox("新建下载")
        input_layout = QVBoxLayout(input_group)
        
        # URL输入
        url_layout = QHBoxLayout()
        url_layout.addWidget(QLabel("视频URL:"))
        self.url_input = QLineEdit()
        self.url_input.setPlaceholderText("请输入视频URL地址...")
        self.url_input.textChanged.connect(self.on_url_changed)
        self.url_input.returnPressed.connect(self.start_download)
        url_layout.addWidget(self.url_input)
        input_layout.addLayout(url_layout)
        
        # URL状态提示
        self.url_status_label = QLabel("")
        self.url_status_label.setStyleSheet("color: #888888; font-size: 11px;")
        input_layout.addWidget(self.url_status_label)
        
        # 文件名输入
        name_layout = QHBoxLayout()
        name_layout.addWidget(QLabel("文件名:"))
        self.name_input = QLineEdit()
        self.name_input.setPlaceholderText("可选，留空自动提取")
        name_layout.addWidget(self.name_input)
        input_layout.addLayout(name_layout)
        
        # 保存路径
        path_layout = QHBoxLayout()
        path_layout.addWidget(QLabel("保存到:"))
        self.path_input = QLineEdit()
        self.path_input.setText(self.config.get("download_path", ""))
        self.path_input.setPlaceholderText("选择保存目录")
        
        browse_btn = QPushButton("浏览...")
        browse_btn.setObjectName("browseButton")
        browse_btn.clicked.connect(self.browse_save_path)
        
        path_layout.addWidget(self.path_input)
        path_layout.addWidget(browse_btn)
        input_layout.addLayout(path_layout)
        
        # 下载按钮
        self.download_btn = QPushButton("开始下载")
        self.download_btn.setObjectName("downloadButton")
        self.download_btn.clicked.connect(self.start_download)
        self.download_btn.setEnabled(False)
        input_layout.addWidget(self.download_btn)
        
        right_layout.addWidget(input_group)
        
        # 详情组
        details_group = QGroupBox("下载详情")
        details_layout = QVBoxLayout(details_group)
        
        # 详情文本
        self.details_text = QTextEdit()
        self.details_text.setReadOnly(True)
        self.details_text.setMaximumHeight(200)
        details_layout.addWidget(self.details_text)
        
        # 总体进度
        progress_layout = QHBoxLayout()
        progress_layout.addWidget(QLabel("总进度:"))
        self.overall_progress = QProgressBar()
        progress_layout.addWidget(self.overall_progress)
        details_layout.addLayout(progress_layout)
        
        right_layout.addWidget(details_group)
        
        # 统计信息组
        stats_group = QGroupBox("统计信息")
        stats_layout = QVBoxLayout(stats_group)
        
        self.stats_label = QLabel("下载任务: 0 | 进行中: 0 | 已完成: 0 | 失败: 0")
        self.stats_label.setStyleSheet("font-weight: bold;")
        stats_layout.addWidget(self.stats_label)
        
        right_layout.addWidget(stats_group)
        
        return right_widget

    # 核心功能方法
    def start_download(self):
        """开始下载"""
        url = self.url_input.text().strip()
        if not url:
            QMessageBox.warning(self, "警告", "请输入视频URL地址")
            return
        
        # 验证URL
        if not URLValidator.is_valid_url(url):
            QMessageBox.warning(self, "警告", "请输入有效的URL地址")
            return
        
        # 检查是否是视频URL（可选警告）
        if not URLValidator.is_video_url(url):
            reply = QMessageBox.question(
                self, "确认", 
                "这个URL可能不是视频链接，确定要下载吗？",
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
            )
            if reply == QMessageBox.StandardButton.No:
                return
        
        # 获取文件名
        filename = self.name_input.text().strip()
        if not filename:
            filename = URLValidator.extract_filename_from_url(url)
        else:
            filename = FileHelper.ensure_extension(filename)
        
        # 获取保存路径
        save_path = self.path_input.text().strip()
        if not save_path:
            save_path = self.config.get("download_path", os.getcwd())
        
        if not os.path.exists(save_path):
            QMessageBox.warning(self, "警告", "保存路径不存在")
            return
        
        # 创建下载任务
        task_id = str(uuid.uuid4())
        if self.downloader.add_download(task_id, url, save_path, filename):
            if self.downloader.start_download(task_id):
                # 添加到表格
                self.add_download_to_table(task_id, filename)
                
                # 清空输入
                self.url_input.clear()
                self.name_input.clear()
                
                # 更新状态
                self.status_bar.showMessage(f"开始下载: {filename}")
                self.details_text.append(f"[{datetime.now().strftime('%H:%M:%S')}] 开始下载: {url}")
                
                log_manager.log_ui_action("开始下载", f"URL: {url}, 文件名: {filename}")
            else:
                QMessageBox.warning(self, "错误", "无法启动下载，可能已达到最大并发数")
        else:
            QMessageBox.critical(self, "错误", "创建下载任务失败")
    
    def pause_download(self):
        """暂停下载"""
        task_id = self.get_selected_task_id()
        if task_id and self.downloader.pause_download(task_id):
            self.update_button_states()
            self.status_bar.showMessage("下载已暂停")
    
    def resume_download(self):
        """恢复下载"""
        task_id = self.get_selected_task_id()
        if task_id and self.downloader.resume_download(task_id):
            self.update_button_states()
            self.status_bar.showMessage("下载已恢复")
    
    def cancel_download(self):
        """取消下载"""
        task_id = self.get_selected_task_id()
        if task_id:
            reply = QMessageBox.question(
                self, "确认", "确定要取消这个下载吗？",
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
            )
            if reply == QMessageBox.StandardButton.Yes:
                if self.downloader.cancel_download(task_id):
                    self.update_button_states()
                    self.status_bar.showMessage("下载已取消")
    
    def retry_download(self):
        """重试下载"""
        task_id = self.get_selected_task_id()
        if task_id and self.downloader.retry_download(task_id):
            self.update_button_states()
            self.status_bar.showMessage("正在重试下载...")
    
    def remove_download(self):
        """移除下载任务"""
        current_row = self.download_table.currentRow()
        if current_row >= 0:
            task_id = self.download_table.item(current_row, 0).data(Qt.ItemDataRole.UserRole)
            
            reply = QMessageBox.question(
                self, "确认", "确定要移除这个下载任务吗？",
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
            )
            if reply == QMessageBox.StandardButton.Yes:
                self.downloader.remove_task(task_id)
                self.download_table.removeRow(current_row)
                self.update_button_states()
                self.status_bar.showMessage("任务已移除")
    
    def clear_completed_downloads(self):
        """清空已完成的下载"""
        to_remove = []
        for row in range(self.download_table.rowCount()):
            task_id = self.download_table.item(row, 0).data(Qt.ItemDataRole.UserRole)
            task = self.downloader.get_task(task_id)
            if task and task.status == DownloadStatus.COMPLETED:
                to_remove.append((row, task_id))
        
        if to_remove:
            reply = QMessageBox.question(
                self, "确认", f"确定要清空 {len(to_remove)} 个已完成的下载吗？",
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
            )
            if reply == QMessageBox.StandardButton.Yes:
                for row, task_id in reversed(to_remove):
                    self.downloader.remove_task(task_id)
                    self.download_table.removeRow(row)
                self.status_bar.showMessage(f"已清空 {len(to_remove)} 个完成的下载")
    
    # UI 辅助方法
    def add_download_to_table(self, task_id: str, filename: str):
        """添加下载到表格"""
        row = self.download_table.rowCount()
        self.download_table.insertRow(row)
        
        # 文件名
        filename_item = QTableWidgetItem(filename)
        filename_item.setData(Qt.ItemDataRole.UserRole, task_id)
        self.download_table.setItem(row, 0, filename_item)
        
        # 状态
        self.download_table.setItem(row, 1, QTableWidgetItem("等待中"))
        
        # 进度
        self.download_table.setItem(row, 2, QTableWidgetItem("0%"))
        
        # 速度
        self.download_table.setItem(row, 3, QTableWidgetItem("-"))
        
        # 大小
        self.download_table.setItem(row, 4, QTableWidgetItem("-"))
    
    def get_selected_task_id(self) -> str:
        """获取选中的任务ID"""
        current_row = self.download_table.currentRow()
        if current_row >= 0:
            return self.download_table.item(current_row, 0).data(Qt.ItemDataRole.UserRole)
        return None
    
    def update_button_states(self):
        """更新按钮状态"""
        task_id = self.get_selected_task_id()
        if not task_id:
            self.pause_btn.setEnabled(False)
            self.resume_btn.setEnabled(False)
            self.cancel_btn.setEnabled(False)
            self.retry_btn.setEnabled(False)
            self.remove_btn.setEnabled(False)
            return
        
        task = self.downloader.get_task(task_id)
        if not task:
            return
        
        self.pause_btn.setEnabled(task.status == DownloadStatus.DOWNLOADING)
        self.resume_btn.setEnabled(task.status == DownloadStatus.PAUSED)
        self.cancel_btn.setEnabled(task.is_active())
        self.retry_btn.setEnabled(task.status == DownloadStatus.FAILED)
        self.remove_btn.setEnabled(not task.is_active())
    
    def update_status_display(self):
        """更新状态显示"""
        tasks = self.downloader.get_all_tasks()
        
        total = len(tasks)
        downloading = len([t for t in tasks.values() if t.status == DownloadStatus.DOWNLOADING])
        completed = len([t for t in tasks.values() if t.status == DownloadStatus.COMPLETED])
        failed = len([t for t in tasks.values() if t.status == DownloadStatus.FAILED])
        
        self.stats_label.setText(f"下载任务: {total} | 进行中: {downloading} | 已完成: {completed} | 失败: {failed}")
        
        # 更新总体进度
        if total > 0:
            total_progress = sum(t.progress for t in tasks.values()) / total
            self.overall_progress.setValue(int(total_progress))
        else:
            self.overall_progress.setValue(0)
    
    # 事件处理方法
    def browse_save_path(self):
        """浏览保存路径"""
        directory = QFileDialog.getExistingDirectory(self, "选择保存目录", self.path_input.text())
        if directory:
            self.path_input.setText(directory)
            self.config.set("download_path", directory)
            self.config.save_config()
    
    def focus_url_input(self):
        """聚焦到URL输入框"""
        self.url_input.setFocus()
    
    def on_url_changed(self):
        """URL输入改变时的处理"""
        url = self.url_input.text().strip()
        if not url:
            self.url_status_label.setText("")
            self.download_btn.setEnabled(False)
            return
        
        if URLValidator.is_valid_url(url):
            if URLValidator.is_video_url(url):
                self.url_status_label.setText("✓ 有效的视频URL")
                self.url_status_label.setStyleSheet("color: #27ae60; font-size: 11px;")
            else:
                self.url_status_label.setText("⚠ 可能不是视频URL")
                self.url_status_label.setStyleSheet("color: #f39c12; font-size: 11px;")
            self.download_btn.setEnabled(True)
        else:
            self.url_status_label.setText("✗ 无效的URL格式")
            self.url_status_label.setStyleSheet("color: #e74c3c; font-size: 11px;")
            self.download_btn.setEnabled(False)
    
    def on_download_selected(self):
        """下载项被选中时的处理"""
        self.update_button_states()
        
        task_id = self.get_selected_task_id()
        if task_id:
            task = self.downloader.get_task(task_id)
            if task:
                self.details_text.clear()
                self.details_text.append(f"任务ID: {task_id}")
                self.details_text.append(f"文件名: {task.filename}")
                self.details_text.append(f"URL: {task.url}")
                self.details_text.append(f"保存路径: {task.save_path}")
                self.details_text.append(f"状态: {task.status.value}")
                self.details_text.append(f"进度: {task.progress}%")
                if task.total_bytes > 0:
                    self.details_text.append(f"大小: {FileHelper.format_file_size(task.total_bytes)}")
                if task.speed > 0:
                    self.details_text.append(f"速度: {FileHelper.format_speed(task.speed)}")
                if task.error_message:
                    self.details_text.append(f"错误: {task.error_message}")

    # 下载器信号处理
    @pyqtSlot(str, int, int, int, float)
    def on_download_progress(self, task_id: str, progress: int, downloaded: int, total: int, speed: float):
        """处理下载进度更新"""
        # 更新表格
        for row in range(self.download_table.rowCount()):
            if self.download_table.item(row, 0).data(Qt.ItemDataRole.UserRole) == task_id:
                self.download_table.setItem(row, 2, QTableWidgetItem(f"{progress}%"))
                self.download_table.setItem(row, 3, QTableWidgetItem(FileHelper.format_speed(speed)))
                if total > 0:
                    self.download_table.setItem(row, 4, QTableWidgetItem(FileHelper.format_file_size(total)))
                break
    
    @pyqtSlot(str, str)
    def on_download_status_changed(self, task_id: str, status: str):
        """处理下载状态更新"""
        status_map = {
            "pending": "等待中",
            "downloading": "下载中",
            "paused": "已暂停",
            "completed": "已完成",
            "failed": "已失败",
            "cancelled": "已取消"
        }
        
        # 更新表格
        for row in range(self.download_table.rowCount()):
            if self.download_table.item(row, 0).data(Qt.ItemDataRole.UserRole) == task_id:
                self.download_table.setItem(row, 1, QTableWidgetItem(status_map.get(status, status)))
                break
        
        # 更新按钮状态
        if task_id == self.get_selected_task_id():
            self.update_button_states()
    
    @pyqtSlot(str, bool, str)
    def on_download_complete(self, task_id: str, success: bool, file_path: str):
        """处理下载完成"""
        if success:
            self.details_text.append(f"[{datetime.now().strftime('%H:%M:%S')}] 下载完成: {file_path}")
            self.status_bar.showMessage(f"下载完成: {os.path.basename(file_path)}")
            
            # 显示成功通知（可选）
            if self.config.get("show_notifications", True):
                self.show_notification("下载完成", f"文件已保存到: {file_path}")
    
    @pyqtSlot(str, str)
    def on_download_error(self, task_id: str, error_message: str):
        """处理下载错误"""
        self.details_text.append(f"[{datetime.now().strftime('%H:%M:%S')}] 下载错误: {error_message}")
        self.status_bar.showMessage(f"下载失败: {error_message}")
        
        # 显示错误通知
        if self.config.get("show_notifications", True):
            self.show_notification("下载失败", error_message)
    
    # 辅助功能方法
    def show_notification(self, title: str, message: str):
        """显示通知消息"""
        # 简单的消息框通知
        msg = QMessageBox(self)
        msg.setWindowTitle(title)
        msg.setText(message)
        msg.setStandardButtons(QMessageBox.StandardButton.Ok)
        msg.setDefaultButton(QMessageBox.StandardButton.Ok)
        msg.show()
        
        # 自动关闭通知
        QTimer.singleShot(3000, msg.close)
    
    def show_preferences(self):
        """显示偏好设置对话框"""
        # 简单的设置对话框（可以后续扩展）
        QMessageBox.information(self, "设置", "偏好设置功能将在未来版本中实现")
    
    def show_logs(self):
        """显示日志文件"""
        log_dir = "logs"
        if os.path.exists(log_dir):
            if sys.platform == "darwin":  # macOS
                os.system(f"open {log_dir}")
            elif sys.platform == "win32":  # Windows
                os.system(f"start {log_dir}")
            else:  # Linux
                os.system(f"xdg-open {log_dir}")
        else:
            QMessageBox.information(self, "信息", "日志目录不存在")
    
    def show_about(self):
        """显示关于对话框"""
        about_text = """
        <h2>VideoGrabber</h2>
        <p>专业的视频下载工具</p>
        <p><b>版本:</b> 2.0.0</p>
        <p><b>作者:</b> VideoGrabber Team</p>
        <p><b>功能特色:</b></p>
        <ul>
        <li>支持多线程下载</li>
        <li>断点续传</li>
        <li>下载管理（暂停、取消、重试）</li>
        <li>URL验证</li>
        <li>日志记录</li>
        <li>配置管理</li>
        </ul>
        <p><b>技术支持:</b> 基于PyQt6和Python</p>
        """
        QMessageBox.about(self, "关于 VideoGrabber", about_text)
    
    # 设置管理
    def load_settings(self):
        """加载设置"""
        # 加载窗口几何
        geometry = self.config.get("window_geometry")
        if geometry:
            self.setGeometry(geometry["x"], geometry["y"], geometry["width"], geometry["height"])
        
        # 加载下载路径
        download_path = self.config.get("download_path")
        if download_path and os.path.exists(download_path):
            self.path_input.setText(download_path)
    
    def save_settings(self):
        """保存设置"""
        # 保存窗口几何
        geometry = self.geometry()
        self.config.set("window_geometry", {
            "x": geometry.x(),
            "y": geometry.y(),
            "width": geometry.width(),
            "height": geometry.height()
        })
        
        # 保存下载路径
        download_path = self.path_input.text().strip()
        if download_path:
            self.config.set("download_path", download_path)
        
        self.config.save_config()
    
    # 事件重载
    def closeEvent(self, event):
        """窗口关闭事件"""
        # 检查是否有正在进行的下载
        active_tasks = [t for t in self.downloader.get_all_tasks().values() if t.is_active()]
        
        if active_tasks:
            reply = QMessageBox.question(
                self, '确认退出',
                f'仍有 {len(active_tasks)} 个下载任务在进行中，确定要退出吗？',
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
                QMessageBox.StandardButton.No
            )
            if reply == QMessageBox.StandardButton.No:
                event.ignore()
                return
        
        # 保存设置
        self.save_settings()
        
        # 停止所有下载
        for task in active_tasks:
            self.downloader.cancel_download(task.task_id)
        
        # 停止定时器
        self.status_timer.stop()
        
        log_manager.log_ui_action("应用退出")
        event.accept()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    
    # 设置应用信息
    app.setApplicationName("VideoGrabber")
    app.setApplicationVersion("2.0.0")
    app.setOrganizationName("VideoGrabber Team")
    
    try:
        # 加载样式文件
        with open("./styles/main.qss", "r", encoding="utf-8") as f:
            app.setStyleSheet(f.read())
        print("[✓] 样式文件加载成功")
    except FileNotFoundError:
        print("[⚠] 警告: 样式文件未找到，使用默认样式")
    except Exception as e:
        print(f"[✗] 错误: 加载样式文件失败: {e}")
    
    try:
        # 创建主窗口
        window = VideoDownloaderApp()
        window.show()
        
        print("[✓] VideoGrabber 启动成功")
        print("[ℹ] 日志文件保存在 logs 目录")
        print("[ℹ] 配置文件: config.json")
        
        # 运行应用
        sys.exit(app.exec())
        
    except Exception as e:
        print(f"[✗] 严重错误: 应用启动失败: {e}")
        log_manager.log_error("Main", f"应用启动失败: {e}", e)
        sys.exit(1)